<?php
class Group_model extends CI_Model {

  public function __construct()
  {
    $this->load->database();

  }

  public function existStoreKey($store_key)
  {
    $sql = "select count(*) as num from group_purchase where store_key = '" . $store_key . "' and group_state != 5";
    $query = $this->db->query($sql);
    $result = $query->row_array();
    if ($result['num'] == 0)
      return False;
    return True;
  }

  public function get_groups($store_key="")
  {
    if($store_key == "")
      $query = $this->db->query("select * from group_purchase where group_state != 5 order by group_state,group_id");
    else
    {
      $sql = "select * from group_purchase where group_state != 5 and store_key = ? order by group_state,group_id"; 
      $query = $this->db->query($sql, array($store_key));
    }
    return $query->result_array();
  }

  public function get_group_versions($group_his_id)
  {
    $sql = "select * from group_purchase where group_his_id=? order by group_state,group_id desc"; 
    $query = $this->db->query($sql, array($group_his_id));
    return $query->result_array();
  }

  //get avaiable group purchases
  public function get_avaGroups() 
  {
    $this->db->where('group_state', 1);
    $query = $this->db->get('group_purchase');
    return $query->result_array();
  }

  public function get_group($group_id)
  {
    $this->db->where('group_id', $group_id);
    $query = $this->db->get('group_purchase');
    return $query->row_array();
  }

  public function new_group($pic_address)
  {
    $buy_deadline = $this->input->post('buy_deadline');
    $use_deadline = $this->input->post('use_deadline');
    $data = array(
        'group_name' => $this->input->post('group_name'),
        'logo_pic' => $pic_address,
        'group_price' => $this->input->post('group_price'),
        'brief_des' => $this->input->post('brief_des'),
        'detail_des' => $this->input->post('detail_des'),
        'buy_deadline' => $buy_deadline,
        'use_deadline' => $use_deadline,
        'group_capacity' => $this->input->post('group_capacity'),
        'user_capacity' => $this->input->post('user_capacity'),
        'use_guide' => $this->input->post('use_guide'),
        'per_user_num' => $this->input->post('per_user_num'),
        'per_user_capacity' => $this->input->post('per_user_capacity'),
        'store_name' => $this->input->post('store_name'),
        'store_phone' => $this->input->post('store_phone'),
        'store_addr' => $this->input->post('store_addr'),
        'group_state' => $this->chargeState($buy_deadline,$use_deadline),
        'store_key' => $this->input->post('3rdKey'),
    );
    $this->db->insert('group_purchase', $data);
    $group_id = $this->db->insert_id();
    $data2 = array(
        'group_his_id' => $group_id,
    );
    $this->db->where('group_id', $group_id);
    $this->db->update('group_purchase', $data2);
    return "添加成功";
  }

  public function update_group($pic_address)
  {
    $changeId = $this->input->get('group_id', TRUE);
    if ($changeId == '')
      return "group_id为空。"; 
    
    $old_data = array(
      'group_state' => 5,
    );
    $this->db->where('group_id', $changeId);
    $this->db->update('group_purchase', $old_data);
    $old_group = $this->get_group($changeId);

    $data = array();
    if ($pic_address == '')
    {
      $buy_deadline = $this->input->post('buy_deadline');
      $use_deadline = $this->input->post('use_deadline');
      $data = array(
        'group_name' => $this->input->post('group_name'),
        'group_price' => $this->input->post('group_price'),
        'brief_des' => $this->input->post('brief_des'),
        'detail_des' => $this->input->post('detail_des'),
        'buy_deadline' => $buy_deadline,
        'use_deadline' => $use_deadline,
        'group_capacity' => $this->input->post('group_capacity'),
        'user_capacity' => $this->input->post('user_capacity'),
        'use_guide' => $this->input->post('use_guide'),
        'per_user_num' => $this->input->post('per_user_num'),
        'per_user_capacity' => $this->input->post('per_user_capacity'),
        'store_name' => $this->input->post('store_name'),
        'store_phone' => $this->input->post('store_phone'),
        'store_addr' => $this->input->post('store_addr'),
        'group_state' => $this->chargeState($buy_deadline,$use_deadline),
        'logo_pic' => $old_group['logo_pic'],
        'buy_num' => $old_group['buy_num'],
        'user_num' => $old_group['user_num'],
        'group_his_id' => $old_group['group_his_id'],
        'store_key' => $this->input->post('3rdKey'),
      );
    }
    else
    {
      $buy_deadline = $this->input->post('buy_deadline');
      $use_deadline = $this->input->post('use_deadline');
      $data = array(
        'group_name' => $this->input->post('group_name'),
        'logo_pic' => $pic_address,
        'group_price' => $this->input->post('group_price'),
        'brief_des' => $this->input->post('brief_des'),
        'detail_des' => $this->input->post('detail_des'),
        'buy_deadline' => $buy_deadline,
        'use_deadline' => $use_deadline,
        'group_capacity' => $this->input->post('group_capacity'),
        'user_capacity' => $this->input->post('user_capacity'),
        'use_guide' => $this->input->post('use_guide'),
        'per_user_num' => $this->input->post('per_user_num'),
        'per_user_capacity' => $this->input->post('per_user_capacity'),
        'store_name' => $this->input->post('store_name'),
        'store_phone' => $this->input->post('store_phone'),
        'store_addr' => $this->input->post('store_addr'),
        'group_state' => $this->chargeState($buy_deadline,$use_deadline),
        'buy_num' => $old_group['buy_num'],
        'user_num' => $old_group['user_num'],
        'group_his_id' => $old_group['group_his_id'],
        'store_key' => $this->input->post('3rdKey'),
      );
    } 
    $this->db->insert('group_purchase', $data);
    return "更新成功";
  }

  public function delete_group()
  {
    $deleteId = $this->input->get('group_id', TRUE);
    if ($deleteId == '')
      return;
      
    $data = array(
      'group_state' => 4,
    );
    $this->db->where('group_id', $deleteId);
    return $this->db->update('group_purchase', $data);
  } 

  public function back_group()
  {
    $deleteId = $this->input->get('group_id', TRUE);
    if ($deleteId == '')
      return;
    $this->db->where('group_id', $deleteId);
    $query = $this->db->get('group_purchase');
    $result = $query->row_array();
    $buy = $result['buy_deadline'];
    $use = $result['use_deadline'];

    $data = array(
      'group_state' => $this->chargeState($buy,$use),
    );
    $this->db->where('group_id', $deleteId);
    return $this->db->update('group_purchase', $data);
  } 

  ////////////group_bill相关操作////////////

  public function new_group_bill($userid,$group_key)
  {
    //$billjson = $this->input->post("billjson");
    //$detail = json_decode($billjson, true);
    $group_id = $this->input->post("group_id"); //这里使用post！
    $amount = $this->input->post("groupnum");
    $name = $this->input->post("name");
    $mail = $this->input->post("mail");
    $phone = $this->input->post("phone");
    $note = $this->input->post("note");

    // 判断输入、数量、时间
    if ($userid == "" or $group_id == "" or $name == "" or $phone == "" or $amount <= 0)
    {
      $data['info'] = 0;
      return $data;
    }//由于信息不完整导致下单失败
    $query = $this->db->query("select * from group_bill where user_id = '" . $userid . "' and user_name = '" . $name . "' order by bill_time desc limit 1");
    $query = $query->row_array();
    $time = time();
    if ($query != null)
    {
     if ($query['user_name'] == $name and $query['user_phone'] == $phone and $time - strtotime($query['bill_time']) <= 30)
     {
        $data['info'] = 1;//由于重复下单导致的下单失败
        return $data;
     }
    }
    $group_result = $this->group_model->get_group($group_id);
    if($group_result == null)
    {
      $data['info'] = 4;
      return $data; 
    }
    if(($group_result['group_capacity']-$group_result['buy_num']) < $amount)
    {
      $data['info'] = 5;
      return $data;
    }
    $user_bills_num = $this->get_bills_num($userid,$group_id);
    if(($group_result['per_user_capacity']-$user_bills_num) < $amount)
    {
      $data['info'] = 6;
      return $data;
    }
    $data['group_detail'] = $group_result;
    // 存入数据库
    $bill_data = array(
      'user_id' => $userid,
      'group_id' => $group_id,
      'bill_time' => date('Y-m-d H:i:s', time()),
      'user_name'  => $name,
      //'user_addr' => $address,
      'user_phone' => $phone,
      'user_mail' => $mail,
      'buy_amount' => $amount,
      'bill_gen_key' => $group_key,
      'bill_note' => $note,
      'bill_state' => 0,
    );
    $sql = "select * from group_purchase where group_id=?"; 
    $query = $this->db->query($sql, array($group_id));
    $query_result = $query->row_array();
    $buy_num = $query_result['buy_num'];
    $user_num = $query_result['user_num'];
    $this_buy_num = $query_result['this_buy_num'];
    $this_user_num = $query_result['this_user_num'];
    $group_data = array(
        'buy_num' => $buy_num + $amount,
        'user_num' => $user_num + 1,
        'this_buy_num' => $this_buy_num + $amount,
        'this_user_num' => $this_user_num + 1,
    );
    $this->db->trans_start();
    $this->db->where('group_id', $group_id);
    $this->db->update('group_purchase', $group_data);
    $this->db->insert('group_bill', $bill_data);
    $data['bill_id'] = $this->db->insert_id();
    $this->db->trans_complete();
    if ($this->db->trans_status() == FALSE)
    {
      $data['info'] = 2;
    }
    else
    {
      $data['info'] = 3;//下单成功
    }

    return $data;
  }  

  public function get_group_history($user_id="",$pageid="",$pagelimit="")
  {
    if($pagelimit == "" and $pageid=="" and $user_id=="")
      $query = $this->db->query("select * from group_bill natural join group_purchase order by bill_state,use_time desc,bill_time desc");
    else if ($pageid == "" and $pagelimit == "")
      $query = $this->db->query("select * from group_bill natural join group_purchase where user_id = '" . $user_id . "' order by bill_time desc " );
    else
      $query = $this->db->query("select * from group_bill natural join group_purchase where user_id = '" . $user_id . "' order by bill_time desc limit " . strval(($pageid-1)*$pagelimit) . "," . strval($pagelimit) );
    return $query->result_array();
  }

  public function get_group_ver_history($id,$info)
  {
    if($info == 1)
      $query = $this->db->query("select * from group_bill natural join group_purchase where group_id = " . $id . " order by bill_state,bill_time desc " );
    else
      $query = $this->db->query("select * from group_bill natural join group_purchase where group_his_id = " . $id . " order by bill_state,bill_time desc " );
    return $query->result_array();
  }

  public function count_group_history($user_id)
  {
    $query = $this->db->query("select count(*) as num from group_bill natural join group_purchase where user_id = '" . $user_id . "' order by bill_time desc " );
    $res = $query->row_array();
    return $res['num'];
  }

  public function get_bill($group_bill_id,$user_id)
  { 
    $query = $this->db->query("select * from group_bill natural join group_purchase where user_id = '" . $user_id ."' and group_bill_id = " . $group_bill_id . " order by bill_time desc limit 1" );
    return $query->row_array();
  }

  public function get_bills_num($user_id,$group_id)
  { 
    $query = $this->db->query("select sum(buy_amount) as user_bills from group_bill natural join group_purchase where user_id = '" . $user_id . "' and group_id = " . $group_id . " order by bill_time desc" );
    $result = $query->row_array();
    return $result['user_bills'];
  }

  public function use_bill()
  {
    $deleteId = $this->input->get('group_bill_id', TRUE);
    if ($deleteId == '')
      return;
      
    $data = array(
      'bill_state' => 1,
      'use_time' => date('Y-m-d H:i:s', time()),
    );
    $this->db->where('group_bill_id', $deleteId);
    return $this->db->update('group_bill', $data);
  } 

  public function back_bill()
  {
    $backId = $this->input->get('group_bill_id', TRUE);
    if ($backId == '')
      return;
      
    $data = array(
      'bill_state' => 0,
      'use_time' => null,
    );
    $this->db->where('group_bill_id', $backId);
    return $this->db->update('group_bill', $data);
  } 

  /*********** group_pic START *************/
  public function get_pics($group_id)
  {
    $this->db->where('group_id', $group_id);
    $this->db->where('pic_state', 1);
    $this->db->order_by('group_pic_id');
    $query = $this->db->get('group_pic');
    return $query->result_array();
  }

  public function get_all_pics($group_id)
  {
    $this->db->where('group_id', $group_id);
    //$this->db->where('pic_state', 1);
    $this->db->order_by('pic_state');
    $this->db->order_by('group_pic_id');
    $query = $this->db->get('group_pic');
    return $query->result_array();
  }

  public function new_pic($pic_address,$group_id)
  {
    $data = array(
        'pic_url' => $pic_address,
        'group_id' => $group_id,
    );
    $this->db->insert('group_pic', $data);
    return "添加成功";
  }

  public function hide_pic($pic_id)
  {
    $data = array(
      'pic_state' => 2,
    );
    //$this->db->where('store_id', $store_id);
    $this->db->where('group_pic_id', $pic_id);
    return $this->db->update('group_pic', $data);
  } 

  public function back_pic($pic_id)
  {
    $data = array(
      'pic_state' => 1,
    );
    //$this->db->where('store_id', $store_id);
    $this->db->where('group_pic_id', $pic_id);
    return $this->db->update('group_pic', $data);
  }

  public function delete_pic($pic_id)
  {
    $data = array(
      'pic_state' => 3,
    );
    //$this->db->where('store_id', $store_id);
    $this->db->where('group_pic_id', $pic_id);
    return $this->db->update('group_pic', $data);
  }

  public function update_pic($old_id,$group_id)
  {
    $pics = $this->get_all_pics($old_id);
    foreach ($pics as $pic_item)
    {
      $data = array(
        'pic_url' => $pic_item['pic_url'],
        'group_id' => $group_id,
      );
      $this->db->insert('group_pic', $data);
    }
    return "success";
  }

  /*********** group_pic END *************/


  public function chargeState($buy_deadline,$use_deadline)
  {
    $buy = strtotime($buy_deadline);
    $use = strtotime($use_deadline);
    $now = time();
    if($buy > $use)
      return -1;
    if($now < $buy)
      return 1;
    else if($now >= $use)
      return 3;
    else
      return 2;
  }

  public function haveKey($id,$store_key,$info)
  {
    if($info == 1)
    {
      $query = $this->db->query("select * from group_purchase where group_his_id = " . $id .  " and group_state != 5");
      $result = $query->row_array();
      if($result == null)
        return false;
      if($result['store_key']==$store_key)
        return true;
      else
        return false;
    }
  }


  // public function get_store_mail($store_id)
  // {
  //   $query = $this->db->query("select store_mail from store where store_id=" . $store_id);

  //   if ($query->num_rows() > 0)
  //   {
  //      $row = $query->row(); 

  //      return $row->store_mail;
  //   }
  //   return "invalidstoredi@error.com";
  // }

}